<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-12 14:38:48
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Comprehensive;


use App\Http\Services\Service;
use App\Repositories\EmployeeRepository;
use App\Repositories\PositionRepository;
use App\Repositories\UserRepository;


class PositionService extends Service
    {
    public $details;
    public function __construct(PositionRepository $repository)
        {
        $this->repository = $repository;
        }
    public function list()
        {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        }
    public function info()
        {
        return $this->repository->with(["users" => ['department']])->condition(request())->getOne();
        }
    protected function save()
        {
        $data       = request()->toArray();
        $k          = 1;
        $ids        = array_map(function ($v) use (&$k)
            {
            EmployeeRepository::whereId($v['id'])->first()->update(['sort' => $k]);
            return $v['id'];
            }, $data['users'] ?? []);
        $shift_data = $this->repository->autosave($data);
        $shift_data->users?->filter(function ($v) use ($ids)
            {
            if (!in_array($v->id, $ids)) {
                $v->position_id = 0;
                $v->save();
                }
            });
        return $shift_data;
        }

    protected function delete()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            // if ($v->users()->count() > 0) {
            //     fail("该岗位已被部分员工使用！无法删除!");
            // }
            $v->delete();
            });
        }
    }
